import logging
import logging.handlers
import os


class LogUtil:
    __initialized = False
    __log_util = None

    def __init__(self):
        self.__logger = logging.getLogger('default')

    def logging_level(self, log_level):
        log_level_dict = {
            'critical': logging.CRITICAL,
            'fatal': logging.FATAL,
            'error': logging.ERROR,
            'warning': logging.WARNING,
            'info': logging.INFO,
            'debug': logging.DEBUG,
        }
        return log_level_dict[log_level]

    def init_logger(self, log_level_name='debug', write_to_file=False, log_file_name=None):
        if log_file_name is not None:
            log_dir = os.path.dirname(log_file_name)
            if not os.path.exists(log_dir):
                os.makedirs(log_dir)
        formatter = logging.Formatter('[%(asctime)s][%(process)d][%(thread)d][%(module)s][%(lineno)d][%(levelname)s] %(message)s')
        log_level = self.logging_level(log_level_name.lower())
        self.__logger.setLevel(log_level)
        self.__logger.propagate = False

        sh = logging.StreamHandler()
        sh.setLevel(log_level)
        sh.setFormatter(formatter)
        self.__logger.addHandler(sh)
        
        if write_to_file:
            fh = logging.handlers.TimedRotatingFileHandler(filename=log_file_name, when='MIDNIGHT',
                                                           interval=1, backupCount=30)
            fh.setFormatter(formatter)
            fh.setLevel(log_level)
            self.__logger.addHandler(fh)

    @staticmethod
    def logger(log_level_name='debug', write_to_file=False, log_file_name=None):
        if not LogUtil.__initialized:
            log_util = LogUtil()
            log_util.init_logger(log_level_name=log_level_name, write_to_file=write_to_file, log_file_name=log_file_name)
            LogUtil.__log_util = log_util
            LogUtil.__initialized = True
        return LogUtil.__log_util.__logger
        # return self.__logger


# log_util = LogUtil()
#
# if __name__ == '__main__':
#     log_util.init_logger()
#     logger = log_util.get_logger()
#
#     logger.info("It's me!!!!")
